package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LOrganization;
import com.learn.core.domain.LTheme;
import com.learn.core.domain.LUser;
import com.learn.core.dto.LThemeDTO;
import com.learn.core.service.ILOrganizationService;
import com.learn.core.service.ILThemeService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @auther CodeGenerator
 * @create 2021-03-14 13:16:28
 * @describe 主题前端控制器
 */
@Api("课程主题")
@RestController
@RequestMapping("/manager/theme")
public class LThemeController extends WebController<LTheme> {


    @Autowired
    private ILThemeService iLThemeService;
    @Autowired
    private ILOrganizationService ilOrganizationService;

    //列表
    @ApiOperation(value = "获取列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LTheme> list(@RequestBody LThemeDTO lThemeDTO){
        try {
            if (lThemeDTO==null||lThemeDTO.getPage()==null||lThemeDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lThemeDTO.getPage(),lThemeDTO.getRows());
            QueryWrapper<LTheme> queryWrapper = new QueryWrapper<LTheme>();
            if(lThemeDTO.getThemeId()!=null)
                queryWrapper.eq("parent_node",lThemeDTO.getThemeId());
            else {
                queryWrapper.eq("parent_node",0);
            }
            if(lThemeDTO.getThemeState() != null)
                queryWrapper.eq("theme_state",lThemeDTO.getThemeState());
            Page<LTheme> lThemes = (Page<LTheme>) iLThemeService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lThemes)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LTheme lTheme : lThemes) {
                LOrganization lOrganization = ilOrganizationService.getById(lTheme.getCreateOrg());
                if(null != lOrganization)
                    lTheme.setCreatOrgName(lOrganization.getOrganizationName());
            }
            // 返回
            return new PageResult(lThemes.getTotal(), lThemes, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }


    //新增
    @ApiOperation(value = "添加")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加课程主题", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LTheme lTheme,HttpServletRequest request){
        String token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lTheme!=null) {
                if (StringUtils.isEmpty(lTheme.getThemeName()))
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_THEME_NAME);
                if (StringUtils.isEmpty(lTheme.getParentNode()))
                    lTheme.setParentNode(0);
                lTheme.setCreateTime(new Date());
                lTheme.setCreateUser(userId);
                if (iLThemeService.save(lTheme))
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除
    @ApiOperation(value = "删除")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除课程主题", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LTheme lTheme){
        try {
            if(lTheme!=null){
                if(lTheme.getThemeId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lTheme.getThemeId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LTheme> queryWrapper = new QueryWrapper<LTheme>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LTheme> lThemes = iLThemeService.list(queryWrapper);
            for (int j = 0; j < lThemes.size(); j++) {
                LTheme lTheme = lThemes.get(j);
                ids.add(lTheme.getThemeId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LTheme>();
        queryWrapper.in(true, "Theme_id", ids);
        iLThemeService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新
    @ApiOperation(value = "更新")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新课程主题", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LTheme lTheme, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lTheme!=null){
            lTheme.setUpdateTime(new Date());
            lTheme.setUpdateUser(userId);
            if(iLThemeService.updateById(lTheme)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}

